import { forEach, includes, concat, indexOf, sortBy } from "lodash";

// 过滤、合并
export function mergeRouters(arr) {
  const excludeRouterNames = ["layout"]; // 目前只排除第一层级
  let res = [];
  forEach(arr, (item) => {
    if (includes(excludeRouterNames, item.name)) {
      res = concat(res, item.children);
    } else {
      res = concat(res, [item]);
    }
  });

  return res;
}

// 排序、拼接菜单
export function sortRouters(arr) {
  // 广度递归
  function recursionRouters(routers, parentRouter = {}) {
    forEach(routers, (item) => {
      if (indexOf(item.path, "/") !== 0) {
        if (!parentRouter.path) {
          item.path = `/${item.path}`;
        } else {
          if (indexOf(parentRouter.path, "/") === 0) {
            item.path = `${parentRouter.path}/${item.path}`;
          } else {
            item.path = `/${parentRouter.path}/${item.path}`;
          }
        }
      }

      if (item.children?.length > 0) {
        item.children = sortBy(item.children, ["meta.sort"]);
        recursionRouters(item.children, item);
      }
    });
    return sortBy(routers, ["meta.sort"]);
  }
  return recursionRouters(arr);
}

// 扁平化菜单
export function flattenRouters(arr) {
  let res = [];

  function recursionRouters(routers, parentRouter = {}) {
    forEach(routers, (item) => {
      // start 拼接路由
      if (parentRouter.path === "/") {
        item.path = "/" + item.path;
      } else {
        if (indexOf(item.path, "/") !== 0) {
          item.path = `${parentRouter.path}/${item.path}`;
        }
      }
      res.push({ ...item, children: null });
      // end
      if (item.children?.length > 0) {
        recursionRouters(item.children, item);
      }
    });
  }
  recursionRouters(arr);
  return res;
}
